import 'package:edu/constants/app_strings.dart';
import 'package:edu/pages/course/course_detail/course_detail_page_logic.dart';
import 'package:edu/pages/main_tab/edu/edu_course/edu_course_page_logic.dart';
import 'package:edu/utils/app_theme.dart';
import 'package:edu/utils/database_helper.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class EduCourseTableContentsWidget extends StatelessWidget {
  const EduCourseTableContentsWidget({super.key});

  @override
  Widget build(BuildContext context) {
    return CustomScrollView(
      key: const PageStorageKey('content'),
      slivers: [
        SliverPadding(
          padding: const EdgeInsets.symmetric(horizontal: 16),
          sliver: _buildCourseTitle(context),
        ),
        SliverPadding(
          padding: const EdgeInsets.only(bottom: 20),
          sliver: _buildCourseCategoryUnitsWidget(context),
        ),
      ],
    );
  }

  // 构建课程标题
  Widget _buildCourseTitle(BuildContext context) {
    return Selector<EduCoursePageLogic, bool>(
      selector: (_, logic) => logic.isContentEmpty,
      builder: (context, v, child) {
        if (v) {
          return const SliverToBoxAdapter(child: SizedBox.shrink());
        } else {
          final logic = context.read<EduCoursePageLogic>();
          return SliverToBoxAdapter(
            child: SizedBox(
              width: double.infinity,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const SizedBox(height: 20),
                  Text(
                    logic.courseDetail!.title,
                    style: Theme.of(context).textTheme.titleMedium?.copyWith(
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  const SizedBox(width: 20),
                  Row(
                    children: [
                      Text(
                        logic.courseDetail!.levelTitle,
                        style: Theme.of(context).textTheme.titleSmall?.copyWith(
                          color: AppTheme.shared.greyColor,
                        ),
                      ),
                      const SizedBox(width: 20),
                      Icon(
                        Icons.person_outline,
                        size: 20,
                        color: AppTheme.shared.greyColor,
                      ),
                      Text(
                        logic.courseDetail!.studentCount.toString(),
                        style: Theme.of(context).textTheme.titleSmall?.copyWith(
                          color: AppTheme.shared.greyColor,
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          );
        }
      },
    );
  }

  // 构建课程目录
  Widget _buildCourseCategoryUnitsWidget(BuildContext context) {
    return Selector<EduCoursePageLogic, bool>(
      selector: (_, logic) => logic.isContentEmpty,
      builder: (context, v, child) {
        final logic = context.read<EduCoursePageLogic>();
        final units = logic.categoryUnits;
        return SliverList(
          delegate: SliverChildBuilderDelegate(childCount: units.length, (
            context,
            index,
          ) {
            final unit = units[index];
            var showDivider = true;
            if (index < units.length - 1) {
              if (units[index + 1].isChapter) {
                showDivider = false;
              }
            } else {
              showDivider = false;
            }
            if (unit.isChapter) {
              return _buildCourseChapterUnitWidget(context, unit);
            } else {
              return _buildCourseVideoUnitWidget(context, unit, showDivider);
            }
          }),
        );
      },
    );
  }

  // 构建课程视频
  Widget _buildCourseVideoUnitWidget(
    BuildContext context,
    CourseTableContentUnit unit,
    bool showDivider,
  ) {
    return GestureDetector(
      onTap: () {
        final logic = context.read<EduCoursePageLogic>();
        logic.playVideo(unit.id);
      },
      child: Container(
        margin: const EdgeInsets.symmetric(horizontal: 16),
        padding: const EdgeInsets.only(left: 8, right: 8, top: 8),
        color: Theme.of(context).colorScheme.surface,
        child: Column(
          children: [
            Selector<EduCoursePageLogic, int>(
              selector: (_, logic) => logic.currentVideoId,
              builder: (context, v, child) {
                var style = Theme.of(context).textTheme.titleSmall;
                final IconData icon;
                if (v == unit.id) {
                  style = Theme.of(context).textTheme.titleSmall?.copyWith(
                    color: AppTheme.shared.purchaseTipColor,
                  );
                  icon = Icons.pause_circle_outline;
                } else {
                  icon = Icons.play_circle_outline;
                }
                final videoIconColor = style?.color;
                return Row(
                  children: [
                    Icon(icon, color: videoIconColor, size: 20),
                    const SizedBox(width: 10),
                    Expanded(child: Text(unit.title, style: style)),
                  ],
                );
              },
            ),
            const SizedBox(height: 10),
            Row(
              children: [
                const SizedBox(width: 28),
                // 课程时长
                Text(
                  AppStrings.duration,
                  style: Theme.of(context).textTheme.titleSmall?.copyWith(
                    color: AppTheme.shared.greyColor,
                  ),
                ),
                // 课程具体时长
                Text(
                  unit.timeString ?? '',
                  style: Theme.of(context).textTheme.titleSmall?.copyWith(
                    color: AppTheme.shared.greyColor,
                  ),
                ),
                const Spacer(),
                // 课程进度
                Text(
                  AppStrings.progress,
                  style: Theme.of(context).textTheme.titleSmall?.copyWith(
                    color: AppTheme.shared.greyColor,
                  ),
                ),
                // 课程具体进度
                SizedBox(
                  width: 40,
                  child: Selector<EduCoursePageLogic, int>(
                    selector: (_, logic) => logic.currentVideoId,
                    builder: (context, id, child) {
                      if (id != unit.id) {
                        final color = AppTheme.shared.greyColor;
                        final style = Theme.of(
                          context,
                        ).textTheme.titleSmall?.copyWith(color: color);
                        return FutureBuilder(
                          future: DatabaseHelper.shared.getVideoProgress(
                            unit.id,
                          ),
                          builder: (context, snapshot) {
                            final progress =
                                (snapshot.data)?.round().toInt() ?? 0;
                            return Text(
                              '${progress.toString()}%',
                              style: style,
                              textAlign: TextAlign.right,
                            );
                          },
                        );
                      } else {
                        final color = AppTheme.shared.purchaseTipColor;
                        final style = Theme.of(
                          context,
                        ).textTheme.titleSmall?.copyWith(color: color);
                        return Selector<EduCoursePageLogic, int>(
                          selector: (_, logic) => logic.currentVideoPercent,
                          builder: (context, v, child) {
                            return Text(
                              '${v.toString()}%',
                              style: style,
                              textAlign: TextAlign.right,
                            );
                          },
                        );
                      }
                    },
                  ),
                ),
              ],
            ),
            const SizedBox(height: 16),
            if (showDivider)
              Divider(
                indent: 0,
                height: 1,
                thickness: 0.5,
                color: AppTheme.shared.greyColor,
              ),
          ],
        ),
      ),
    );
  }

  // 构建课程章节
  Widget _buildCourseChapterUnitWidget(
    BuildContext context,
    CourseTableContentUnit unit,
  ) {
    final style = Theme.of(
      context,
    ).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold);
    return Padding(
      padding: const EdgeInsets.only(left: 16, right: 16, top: 20, bottom: 10),
      child: Row(
        children: [
          Expanded(
            child: Text(
              unit.title,
              style: style,
              maxLines: 2,
              overflow: TextOverflow.ellipsis,
            ),
          ),
        ],
      ),
    );
  }
}
